<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\model\UserModel;
use app\model\CategoryModel;
use think\facade\Request;
use think\facade\Validate;
use think\facade\View;

class User
{
    public function index()
    {
        $userList = UserModel::select();
        View::assign('userList', $userList);
        return View::fetch();
    }
    public function add()
    {
        $categoryList = CategoryModel::getAllPreKey();
        return View::fetch('', ['categoryList' => $categoryList]);
    }

    public function addSave()
    {
        $params = Request::param();
        $validate = Validate::rule([
            'user_name|用户名' => 'require|min:2|max:50',
            'user_img|用户头像' => 'require',
        ]);
        if (!$validate->check($params)) {
            echo $validate->getError();
            exit();
        }

        $params['add_time'] = time();
        $params['update_time'] = time();

        $result = UserModel::create($params);

        return View::fetch('public/tips', ['result' => $result]);
    }

    public function edit()
    {
        $userId = Request::param("user_id");
        $validate = Validate::rule([
            'user_id|用户id' => 'require|between:1,' . PHP_INT_MAX,
        ]);
        if (!$validate->check(['user_id' => $userId])) {
            echo $validate->getError();
            exit();
        }

        $user= UserModel::find($userId);
        if (!$user) {
            echo '用户不存在';
            exit();
        }
        return View::fetch('', ['user' => $user]);
    }

    // 保存数据
    public function editSave()
    {
        $params = Request::param();
        $validate = Validate::rule([
            'user_id|用户id' => 'require|between:1,' . PHP_INT_MAX,
            'user_name|用户名' => 'require|min:2|max:50',
            'user_img|用户头像' => 'require',
        ]);
        if (!$validate->check($params)) {
            echo $validate->getError();
            exit();
        }
        
      
        $user = UserModel::find($params['user_id']);
        if (!$user) {
            echo '用户不存在';
            exit();
        }
        $user['user_name'] = $params['user_name'];
        $user['user_img'] = $params['user_img'];
        $user['update_time'] = time();
        $result = $user->save();

        return View::fetch('public/tips', [
            'result' => $result,
        ]);
    }

   
    public function delete()
    {
        $userId = Request::param("user_id");
        $validate = Validate::rule([
            'user_id|用户名' => 'require|between:1,' . PHP_INT_MAX,
        ]);
        if (!$validate->check(['user_id' => $userId])) {
            echo $validate->getError();
            exit();
        }

        $result = UserModel::destroy($userId);
        return View::fetch('public/tips', ['result' => $result]);
    }
}
